package org.jeecg.modules.cascv.image.service.merge;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.service.merge.liangxianggui.LiangxiangguiApp1Service;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 6d21  10:17:58.127  1078127图片获取结束 10:19:03:980:1143980     65853  645  10/s
 * 10:17:56.427 1076427 mq获取结束 10:19:03:971 1143971 67544     9386    139/s
 *
 *6d21: 线程
 *
 *
 *
 * 6d22
 */
@Service
@Slf4j
public class ShoutaoxiangService extends ImageService {
    @Value("${imageurl}")
    private String imageurl;
    @Autowired
    private TaskExecutePool taskExecutePool;

    private AtomicInteger num = new AtomicInteger(0);


    @Override
    public String idsNames() {
        return "6D32H_67H,6D31H_67H,6D21H_64H,6D22H_64H";
    }


    @Override
    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {
        JSONObject content = jsonObject.getJSONObject("Content");


        //打印报错不连续的包序号
        String packageNum = content.getString(LaptopConstant.Package_number_MAP.get(idsName));
        packageNum = packageNum.split(";")[1];
        if(packageNum.endsWith("H")){
            packageNum=packageNum.substring(0,packageNum.length()-1);
        }
        int intpackageNum = Integer.parseInt(packageNum,16);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if(null==lastPackageNum){
            LaptopConstant.packageNumMap.put(key,intpackageNum);
        }else {
            LaptopConstant.packageNumMap.put(key,intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (2511 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:"+intpackageNum+"，上一包包序号:"+lastPackageNum);
                }
            }
        }


        String hexStr = content.getString(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
     //   hexStr = hexStr.substring(7, hexStr.length() - 6);
        hexStr = hexStr.split(";")[1].substring(2).trim();
        String startEndFlag = content.getString(LaptopConstant.STARTEND_FLAG_MAP.get(idsName));
        startEndFlag = startEndFlag.split(";")[0];

        //  hexStr = hexStr.substring(0,hexStr.length()-1);
//        String idsName = jsonObject.getString("idsName");
//        String fileId = jsonObject.getString("fileId");
//        boolean realTimeFlag = StringUtils.isNotBlank(fileId);
//        String key = realTimeFlag ? fileId : idsName;

        if (StringUtils.isBlank(hexStr)) return Result.error("图像数据为空！");
        StringBuilder imageData = LaptopConstant.imageData.get(key);
        if (hexStr.startsWith("FFD8")) {
            imageData = new StringBuilder();
            LaptopConstant.imageData.put(key, imageData);
            imageData.append(hexStr);
        } else if (imageData != null && LaptopConstant.END_FLAG.equalsIgnoreCase(startEndFlag) && hexStr.contains("FFD9")) {
            int endIndex = hexStr.indexOf("FFD9");
          //  String substring = hexStr.substring(0, endIndex + 4);

            while (hexStr.endsWith("BA") && hexStr.contains("FFD9BA")) {
                hexStr = hexStr.substring(0, hexStr.length() - 2);
            }
            imageData.append(hexStr);
            //content.remove("A1_TPSR_MICU_APP5DATA1_16_817_1");
//            int fill = 2006 - (imageData.length() / 2);
//            if (fill > 0) {
//                for (int i = 0; i < fill; i++) {
//                    imageData.append("ba");
//                }
//            }

          //  System.out.println("imageData.length2222 ===> " + imageData.length());

            int length = imageData.toString().toCharArray().length;
            String imgHexStr = imageData.toString();
            CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
                long start = System.currentTimeMillis();
                byte[] result = HexUtil.decodeHex(imgHexStr);
                    //随机字符
                    String idStr = IdWorker.getIdStr();
                    FileUtil.touch("/data/images/" + idStr + ".jpeg");
                    //生成图片
                    try {
                        FileUtil.writeBytes(result, "/data/images/" + idStr + ".jpeg");
                    } catch (Exception e) {
                        log.error("手套箱图片生成失败," + e);
                        e.printStackTrace();
                    }
                    BufferedImage bi = null;
//                int png = LaptopConstant.nativeImageIO.write(result, 1048, 1048, "/data/", idStr + ".png", "png");
                    try {

                        bi = ImageIO.read(new File("/data/images/" + idStr + ".jpeg"));
                        int width = bi.getWidth();
                        int height = bi.getHeight();
                    } catch (Exception e) {
                        log.error("手套箱图片生成失败", e);
                        e.printStackTrace();

                    }
                    num.incrementAndGet();
                //    log.info("图片个数："+num.get());


                    //base64生成图片的方式   String base64 = Base64.getEncoder().encodeToString(FileUtil.readBytes("/data/" + idStr + ".png"));
                    String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" + idStr + ".jpeg";

                  //  log.info(imageUrl);
                 //   System.out.println("imageUrl = " + imageUrl);
                    content.put("imageUrl", imageUrl);
                    content.put("idsName", idsName);

                    String secondStr = jsonObject.getString("second");
                    long second = Long.parseLong(secondStr);
                    String subSecondStr = jsonObject.getString("subsecond");
                    secondStr = LaptopUtil.toDayHoursMinSec(second);

                    String[] split = secondStr.split(":");
                    content.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
                    content.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
                    //将图片名称添加到
//                    List<String> filenamelist = LaptopConstant.imagefilename.get(idsName);
//                    if(null==filenamelist){
//                        filenamelist = new CopyOnWriteArrayList<>();
//                        LaptopConstant.imagefilename.put(idsName,filenamelist);
//                    }
//                    filenamelist.add(idStr + ".jpeg");

                    //将图片添加到map
                    content.put("key", key);
                log.info("手套箱"+idsName+"合成一张图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");
                    return content;
                },taskExecutePool.threadPoolTaskExecutor2());
            LaptopConstant.imageFutureList.add(future);
            LaptopConstant.imageData.remove(key);

        } else if (imageData != null) {
            imageData.append(hexStr);
        }

        return null;
    }

    public static void main(String[] args) {
        System.load("D:/disk1/libjpeg-9.dll");
        System.load("D:/disk1/libpng-3.dll");
        System.load("D:/disk1/NativeImageIOJNI.dll"); //D:\pc_workspace\shoutao2
        List<String> strings = FileUtil.readUtf8Lines("E:\\图像数据\\cut\\手套箱\\T20221115103632_0001_0065_F1_00_6DCD_2024_0064_64_6D22_000000000.txt");
        ShoutaoxiangService shoutaoxiangService = new ShoutaoxiangService();
        for (String string : strings) {
            //将str转化为相应的JSONObject对象
            JSONObject jsonObject = JSONObject.parseObject(string);

            shoutaoxiangService.merge(jsonObject, "6D22H_64H", "6D22H_64H");
        }

    }

}
